//
//  CPAudioPlayerViewForCell.m
//  AFNetworking
//
//  Created by CollegePre on 2018/4/9.
//

#import "CPAudioPlayerViewForCell.h"
#import <AVFoundation/AVFoundation.h>

@interface CPAudioPlayerViewForCell ()
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UILabel *contentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *currentTImeLabel;
@property (nonatomic, strong) NSTimer *progressTimer;
@property (nonatomic, assign) BOOL  isSliderPlay;
@property (nonatomic, strong) UIView *superView;

@end

@implementation CPAudioPlayerViewForCell

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (double)audioPlayProgress{
    if (self.audioPath && self.audioPlayer) {
        return self.audioPlayer.player.currentTime / self.audioPlayer.player.duration;
    }else{
        return 0.0f;
    }
}


- (NSTimer *)progressTimer{
    if (!_progressTimer) {
        _progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(refreshProgressView) userInfo:nil repeats:YES];
    }
    return _progressTimer;
}

- (CPAudioPlayer *)audioPlayer{
    if (!_audioPlayer) {
        _audioPlayer = [[CPAudioPlayer alloc] init];
    }
    return _audioPlayer;
}

// 初始化
+ (instancetype)audioPlayerView{
    
    CPAudioPlayerViewForCell *playerView = [[[NSBundle bundleForClass:[CPAudioPlayerViewForCell class]] loadNibNamed:@"CPAudioPlayerViewForCell" owner:nil options:nil] lastObject];
    
    playerView.progressSlider.value = 0;
    playerView.progressSlider.minimumTrackTintColor = [CPAudioTools audio_colorWithHexString:@"#01B7EE"];
    playerView.progressSlider.maximumTrackTintColor = [CPAudioTools audio_colorWithHexString:@"#EEEEEE"];
    playerView.layer.cornerRadius = 2;
    
    playerView.clipsToBounds = YES;
    
    [playerView.progressSlider setThumbImage:[UIImage imageNamed:@"tuodong"] forState:UIControlStateNormal];
    
    return playerView;
}

- (instancetype)audioPlayerViewWithSuperView:(UIView *)superView{
    self.frame = superView.bounds;
    [superView addSubview:self];
    self.superView = superView;
    return self;
}

- (void)awakeFromNib{
    [super awakeFromNib];
}


- (IBAction)progressSiliderDragEnter:(UISlider *)sender {
    //    NSLog(@"progressSiliderDragEnter");
}

- (IBAction)progressSliderDragExit:(UISlider *)sender {
    //    NSLog(@"progressSliderDragExit");
}
- (IBAction)progressSliderValueChange:(UISlider *)sender {
    //    NSLog(@"progressSliderValueChange");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.duration * sender.value];
    });
}

// 开始拖拽
- (IBAction)touchDown:(UISlider *)sender {
    //    NSLog(@"touchDown");
    
    self.isSliderPlay = self.playBtn.selected;
    
    [self puasePlayAuidoWhenDragSlider];
}
- (IBAction)touchCancel:(UISlider *)sender{
    //    NSLog(@"touchCancel");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    if (self.dragProgressBlock) {
        self.dragProgressBlock(sender.value,self.isSliderPlay);
    }
    
    self.audioPlayer.player.currentTime = self.progressSlider.value * self.audioPlayer.player.duration;
    
    if (self.isSliderPlay) {
        [self continuePlayAudio];
    }
}
- (IBAction)touchDownRepeat:(UISlider *)sender {
    //    NSLog(@"touchDownRepeat");
}

// 拖拽中
- (IBAction)touchDargInside:(UISlider *)sender {
    //    NSLog(@"touchDargInside");
    
    [self puasePlayAuido];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.duration * sender.value];
    });
}
- (IBAction)touchDragOutSide:(UISlider *)sender {
    //    NSLog(@"touchDragOutSide");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    if (self.dragProgressBlock) {
        self.dragProgressBlock(sender.value,self.isSliderPlay);
    }
    
    self.audioPlayer.player.currentTime = self.progressSlider.value * self.audioPlayer.player.duration;
    
    if (self.isSliderPlay) {
        [self continuePlayAudio];
    }
}

// 拖拽结束结束
- (IBAction)touchupInside:(UISlider *)sender {
    //    NSLog(@"touchupInside");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    if (self.dragProgressBlock) {
        self.dragProgressBlock(sender.value,self.isSliderPlay);
    }
    
    self.audioPlayer.player.currentTime = self.progressSlider.value * self.audioPlayer.player.duration;
    
    if (self.isSliderPlay) {
        [self continuePlayAudio];
    }
}


- (IBAction)touchupOutSide:(UISlider *)sender  {
    //    NSLog(@"touchupOutSide");
    if (self.progressBlock) {
        self.progressBlock(sender.value);
    }
    
    if (self.dragProgressBlock) {
        self.dragProgressBlock(sender.value,self.isSliderPlay);
    }
    
    self.audioPlayer.player.currentTime = self.progressSlider.value * self.audioPlayer.player.duration;
    
    if (self.isSliderPlay) {
        [self continuePlayAudio];
    }
}

- (void)setAudioPlayProgress:(double)progress audioPlayState:(BOOL)isPlay{
    self.audioPlayer.player.currentTime = progress * self.audioPlayer.player.duration;
    if (isPlay) {
        [self continuePlayAudio];
    }else{
        [self puasePlayAuido];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.progressSlider.value = progress;
        self.contentTimeLabel.text = [NSString stringWithFormat:@"%@",[self timeWithSeconds:self.audioPlayer.player.duration]] ;
        self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.currentTime];
    });
    
}


- (void)puasePlayAuido{
    [self.audioPlayer pausePlaying];
    [self.progressTimer invalidate];
    self.progressTimer = nil;
    
    self.playBtn.selected = NO;
    
}

- (void)puasePlayAuidoWhenDragSlider{
    [self.audioPlayer pausePlaying];
    [self.progressTimer invalidate];
    self.progressTimer = nil;
    
    
    
}

- (void)continuePlayAudio{
    [self.audioPlayer continuePlaying];
    
    [self.progressTimer fire];
    
    self.playBtn.selected = YES;
}

- (void)stopPlayAudio{
    if (self.audioPlayer.isPlaying) {
        [self.audioPlayer stopPlaying];
        [self.progressTimer invalidate];
        self.progressTimer = nil;
    } else if (self.manualPausePlaying) {
        // 说明是手动暂停的
        [self.audioPlayer.player stop];
        self.audioPlayer.isPausePlaying = NO;
        [self.progressTimer invalidate];
        self.progressTimer = nil;
    }
    self.progressSlider.value = 0.0f;
    self.playBtn.selected = NO;
    self.currentTImeLabel.text = @"00:00";
}

- (void)cancelpressProgressbtn{
    
    if (self.audioPlayer.isPausePlaying) {
        float progress = self.progressSlider.value;
        self.audioPlayer.player.currentTime = self.audioPlayer.player.duration * progress;
        [self.audioPlayer continuePlaying];
        
        [self.progressTimer fire];
    }
    
}

// 开始播放
- (void)startPlayWithAudioPath:(NSString *)path complition:(CPAudioPlayerComplitionBlock)complition{
    self.playBtn.selected = YES;
    if ([self.audioPath isEqualToString:path]) {
        [self continuePlayAudio];
    }else{
        
        BOOL isExit = [[NSFileManager defaultManager] fileExistsAtPath:path];
        if(isExit){
            [self.audioPlayer stopPlaying];
            
            self.audioPath = path;
            [self.audioPlayer startPlayingWithName:path block:^{
                [self.progressTimer invalidate];
                self.progressTimer = nil;
                
                self.progressSlider.value = 0.0f;
                self.currentTImeLabel.text = @"00:00";
                
                self.playBtn.selected = NO;
                self.complitionBlock();
                complition();
                
            }];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.contentTimeLabel.text = [NSString stringWithFormat:@"%@",[self timeWithSeconds:self.audioPlayer.player.duration]] ;
                self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.currentTime];
            });
            
            [self.progressTimer fire];
        }else{
            NSLog(@"audio文件不存在");
            self.playBtn.selected = NO;
            if (self.complitionBlock) {
                self.complitionBlock();
            }
            
            complition();
        }
    }
}


- (void)refreshProgressView{
    float progress = self.audioPlayer.player.currentTime / self.audioPlayer.player.duration;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.progressSlider.value = progress;
        self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.currentTime];
    });
}


// 点击播放按钮
- (IBAction)playBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        // 开始播放
        self.manualPausePlaying = NO;
        if (self.willPlayBlock) {
            self.willPlayBlock();
        }
        if ([self.audioPlayer isPausePlaying]) {
            // TODO: 继续播放
            NSLog(@"继续播放");
            [self.audioPlayer continuePlaying];
        } else {
            // TODO: 第一次开始播放
            NSLog(@"第一次开始播放");
            [self.audioPlayer stopPlaying];
            [self.audioPlayer startPlayingWithName:self.audioPath block:^{
                [self.progressTimer invalidate];
                self.progressTimer = nil;
                self.progressSlider.value = 0.0f;
                self.currentTImeLabel.text = @"00:00";
                sender.selected = NO;
            }];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.contentTimeLabel.text = [NSString stringWithFormat:@"%@",[self timeWithSeconds:self.audioPlayer.player.duration]] ;
                self.currentTImeLabel.text = [self timeWithSeconds:self.audioPlayer.player.currentTime];
            });
        }
        [self.progressTimer fire];
    } else {
        // 暂停播放
        self.manualPausePlaying = YES;
        [self.audioPlayer pausePlaying];
        [self.progressTimer invalidate];
        self.progressTimer = nil;
    }
}

- (NSString *)timeWithSeconds:(NSTimeInterval)seconds{
    NSInteger mints = seconds / 60;
    NSInteger secs = (NSInteger)seconds % 60;
    return [NSString stringWithFormat:@"%02ld:%02ld",(long)mints,(long)secs];
}
- (IBAction)closeBtnClick:(id)sender {
    [self.audioPlayer stopPlaying];
    if (self.closeBlock) {
        self.closeBlock();
    }
}

@end
